<?php
namespace Admin\Model;
use Think\Model;

class DatabaseModel extends Model {
	function backup($name) {
		$dir = C('DATA_BACKUP_PATH').date('Y-m-d/');
		if (!is_dir($dir)) {
			mkdir($dir, 0755, true);
		}else {
			$dir = C('DATA_BACKUP_PATH').date('Y-m-d-H-s/');
			mkdir($dir, 0755, true);
		}
		$lock = $dir.'lock.c';
		if (file_exists($lock)) {
			$this->error = '有一个备份操作正在执行！';
			return false;
		}else {
			file_put_contents($lock, NOW_TIME);
		}
		foreach ($name as $k) {
			$this->backtable($k, $dir, 0);
		}
		if (unlink($lock)){
			return true;
		}
	}
	protected function backtable($table, $dir) {
		$file = $dir.$table.'.sql';
		$db = \Think\Db::getInstance();
		//备份表结构
		$result = $db->query("SHOW CREATE TABLE `{$table}`");
		$sql  = "";
		$sql .= "-- -----------------------------\n";
		$sql .= "-- Table structure for `{$table}`\n";
		$sql .= "-- Backup date ".date('Y-m-d H:i:s')."\n";
		$sql .= "-- -----------------------------\n";
		$sql .= "DROP TABLE IF EXISTS `{$table}`;\n";
		$sql .= trim($result[0]['Create Table']) . ";\n\n";
		//数据总数 
		$sql = str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $sql);
		
		$resultcount = $db->query("SELECT COUNT(*) AS count FROM `{$table}`");
		$count  = $resultcount['0']['count'];
		if ($count) {
			//写入数据注释
			$sql .= "-- -----------------------------\n";
			$sql .= "-- Records of `{$table}` Rows:{$count}\n";
			$sql .= "-- -----------------------------\n";
			//备份数据记录
			$recordresult = $db->query("SELECT * FROM `{$table}`");
			$sql .= "INSERT INTO `{$table}` VALUES ";
			foreach ($recordresult as $row) {
				$row = array_map('mysql_real_escape_string', $row);
				$sql .= "('" . implode("', '", $row) . "'),\n";
			}
			$sql = rtrim($sql,",\n").';';
		}
		if (!file_put_contents($file, $sql)) return false;
	}
	
	function lists() {
		$tables = M()->query('SHOW TABLE STATUS');
		return $tables;
	}
}